use Test::More tests => 28;
use File::Spec;
use Zim::File;

$SIG{__WARN__} = sub {
	print STDERR @_ unless $_[0] =~ /^#/;
};

my $f = File::Spec->rel2abs(
	File::Spec->catfile('t', 'test_file.txt~') );
unlink $f;

my $file = Zim::File->new('t', 'test_file.txt~');

ok(! $file->exists, 'clean start'); #1
my $path = $file->path;
ok($path =~ m#/t/test_file.txt~$#, 'path'); # 2
ok("$file" eq $path, 'overload'); # 3
ok(-d $file->dir, 'dir'); #4
ok($file->file eq 'test_file.txt~', 'file'); #5

$file->write("test 123\ntest 456\n");
ok( cat($f) eq "test 123\ntest 456\n", 'write'); #6
$file->append("test 789\n");
ok( cat($f) eq "test 123\ntest 456\ntest 789\n", 'append'); #7

ok($file->read eq "test 123\ntest 456\ntest 789\n", 'read scalar'); #8
is_deeply(
	[$file->read],
	["test 123\n","test 456\n","test 789\n"],
	'read list' ); #9

ok($file->exists, 'exists'); #10
$file->remove();
ok(! -e $f && ! $file->exists, 'remove'); #11

$file->write_config({a => 1, b => 3, c => 2}, [qw/a c b/]);
ok(cat($f) eq "a=1\nc=2\nb=3\n", 'write_config'); #12
is_deeply(
	[$file->read_config()],
	[{a => 1, b => 3, c => 2}, [qw/a c b/]],
	'read_config' ); #13

my $io = $file->open;
ok($io->isa('IO::File'), 'open'); #14
close $io;

my $check = 0;
$file->signal_connect(write => sub { $check = 1});
$io = $file->open('w'); 
print $io "Test 123\n";
$io->close;
ok($check, 'callback on close'); # 15

$file->remove;

my $dir = File::Spec->catdir(qw/t test_file foo bar baz/);
my $parent = File::Spec->catdir(qw/t test_file/);
Zim::File->remove_dir($dir) if -d $dir;
Zim::File->make_dir($dir);
ok(-d $dir, 'make_dir'); #16
Zim::File->remove_dir($dir);
ok(! -e $dir && ! -e $parent, 'remove_dir'); #17

# Uris
my @uris = (
	['file:///foo/bar', '/foo/bar'],
	['file:/foo/bar', '/foo/bar'],
	['file://localhost/foo/bar', '/foo/bar'],
	['file://foo/bar', 'file://foo/bar'],
);
SKIP: {
	skip("Win32 specific parsing", 5) unless $^O eq 'MSWin32';

	push @uris,
	['file:///C:/foo', 'C:/foo'], # and not /C:/foo
	['file:////foo/bar', 'smb://foo/bar'] ;

	my $i = 0;
	ok(Zim::File->localize($$_[0]) eq $$_[1], "win32 localize ".++$i) for
		['C:/foo/bar', 'C:\foo\bar'],
		['smb://foo/bar', '\\\\foo\bar'] ;

	my $f = "C:\\foo\\bar";
	$f = Zim::File->path2uri($f);
	$f = Zim::File->parse_uri($f);
	$f = Zim::File->localize($f);
	ok($f eq "C:\\foo\\bar", 'win32 uri round trip');
};

my $i = 0;
ok(Zim::File->parse_uri($$_[0]) eq $$_[1], 'parse_uri '.++$i) for @uris;

my @path = ($^O eq 'MSWin32')
	? ('/foo//bar\../c/d/e\.././../q/./baz', 'C:/xx', 'C:/foo/c/q/baz')
	: ('/foo//bar/../c/d/e/.././../q/./baz', 'x', '/foo/c/q/baz') ;
ok(Zim::File->abs_path($path[0], $path[1]) eq $path[2], 'path cleanup 1');
ok(length Zim::File->abs_path('/../../../'), 'path cleanup 2');

exit;

sub cat {
	my $file = shift;
	open FILE, $file or die $!;
	my $content = join '', <FILE>;
	close FILE;
	return $content;
}

